package com.neuedu.controller;


import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;

import com.neuedu.config.AlipayConfig;
import com.neuedu.util.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/pay")
@SuppressWarnings("rawtypes")

public class PayController {

    private Logger log = LoggerFactory.getLogger(PayController.class);

    @Autowired
    private AlipayConfig alipayConfig;

    /**
     * 测试订单号15932466191022,15933410263042
     localhost:8082/user/payByAli/15933410263042
     * url localhost:8082/user/payByAli/159325916488
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @GetMapping("/payDemo/{money}")
    public void payByMoney(@PathVariable BigDecimal money,HttpServletRequest request, HttpServletResponse response) throws Exception {
        Date currDate = new Date();

        //获取当时时间戳
        long timestamp = Date.parse(String.valueOf(currDate)); //155866554500

        //生成订单
//        String orderId = (String) timestamp; //20190524155866554500
        String orderId = String.valueOf(timestamp);
        payController(orderId,request,response,money);

    }


    private void payController(String orderNo, HttpServletRequest request, HttpServletResponse response, BigDecimal money)
            throws Exception {

        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getOpenApiDomain(), alipayConfig.getAppId(),
                alipayConfig.getMerchantPrivateKey(), alipayConfig.getFormat(), alipayConfig.getCharset(),
                alipayConfig.getAlipayPublicKey(), alipayConfig.getSignType()); // 获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();// 创建API对应的request
        alipayRequest.setReturnUrl(alipayConfig.getReturnUrl());
        alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());// 在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" + "    \"out_trade_no\":\"" + orderNo + "\","
                + "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," + "    \"total_amount\":\""
                + money + "\"," + "    \"subject\":\"" + "捐赠" + "\","
                + "    \"body\":\"" + "遇到问题，客服7*24为你解答问题" + "\","
                + "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\","
                + "    \"extend_params\":{" + "    \"sys_service_provider_id\":\"2088511833207846\"" + "    }" + "  }");// 填充业务参数
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {

            log.debug("支付失败");

        }
        response.setContentType("text/html;charset=" + alipayConfig.getCharset());
        response.getWriter().write(form);// 直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    @RequestMapping("/return")
    public void  paySuccess(String out_trade_no,HttpServletResponse response,HttpServletRequest request) throws Exception{
        Map<String, String> map = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            map.put(name, valueStr);
        }

        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(map, alipayConfig.getAlipayPublicKey(),
                    alipayConfig.getCharset(), alipayConfig.getSignType());
        } catch (AlipayApiException e) {
            log.info("支付回调异常",e);
            // 验签发生异常,则直接返回失败
            //response.sendRedirect("/");
            System.out.println("验证异常");
        }
        if (signVerified) {

            response.sendRedirect("http://localhost:81/#/project");
            System.out.println("验证成功");
        } else {
            log.info("验证失败");
            //response.sendRedirect("http://localhost:8082/rlg/payFail.html");
            System.out.println("验证失败");
        }
    }

    @RequestMapping("/notify")
    public void payNotify(String out_trade_no,HttpServletResponse response,HttpServletRequest request
    )throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            map.put(name, valueStr);
        }

        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(map, alipayConfig.getAlipayPublicKey(),
                    alipayConfig.getCharset(), alipayConfig.getSignType());
        } catch (AlipayApiException e) {
            log.info("支付回调异常",e);
            // 验签发生异常,则直接返回失败

            //response.sendRedirect("/rlg/payFail.html");

        }
        if (signVerified) {

            //response.sendRedirect("/rlg/paySuccess.html");
            System.out.println("验证成功");
        } else {
            log.info("验证失败");

           // response.sendRedirect("/rlg/payFail.html");
        }
    }

}